//
//  UIBarButtonItem+Extension.swift
//  WeiBo14
//
//  Created by HM on 16/3/2.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit


extension UIBarButtonItem {
    
    /// 快速的创建一个 UIBarButtonItem
    ///
    /// - parameter imageNamed: 显示的图标名字
    /// - parameter target:     事件触发的时候调用谁的方法
    /// - parameter action:     调用哪个方法
    ///
    /// - returns: <#return value description#>
    convenience init(imageNamed: String? = nil, title: String? = nil, target: AnyObject?, action: Selector) {
        self.init()
        // 初始化button
        let button = UIButton()
        
        // 添加点击事件
        button.addTarget(target, action: action, forControlEvents: .TouchUpInside)
        
        
        // 如果 title 有值,那么就去设置文字
        if let t = title {
            // 设置文字
            button.setTitle(t, forState: UIControlState.Normal)
            // 设置不同状态的文字颜色
            button.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
            button.setTitleColor(UIColor(colorLiteralRed: 52/255, green: 52/255, blue: 52/255, alpha: 1), forState: .Normal)
            // 设置字体大小
            button.titleLabel?.font = UIFont.systemFontOfSize(14)
        }
        
        if let named = imageNamed {
            // 设置不同状态的图片
            button.setImage(UIImage(named: named), forState: UIControlState.Normal)
            button.setImage(UIImage(named: "\(named)_highlighted"), forState: UIControlState.Highlighted)
        }
        button.sizeToFit()
        customView = button
    }
}
